package nongchang.kuaijiecaifu.com.ncapp_android.ui.adapter;

/**
 * Created by Administrator on 2016/3/3 0003.
 */

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

import ezy.lite.util.DateTime;
import ezy.lite.util.UI;
import nongchang.kuaijiecaifu.com.ncapp_android.R;
import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.data.HomeCartManager;
import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.good.AllCart;
import nongchang.kuaijiecaifu.com.ncapp_android.retrofit.good.HomeItemCart;

/**
 * Created by Administrator on 2016/3/3 0003.
 */
public class MyExpandableListViewAdapter extends BaseExpandableListAdapter {

    private Context context;
    private List<AllCart> group_list;


    public MyExpandableListViewAdapter(Context context, List<AllCart> list) {
        this.context = context;
        this.group_list = list;
    }



    /**
     * 获取组的个数
     *
     * @return
     * @see android.widget.ExpandableListAdapter#getGroupCount()
     */
    @Override
    public int getGroupCount() {
        return group_list.size();
    }

    /**
     * 获取指定组中的子元素个数
     *
     * @param groupPosition
     * @return
     * @see android.widget.ExpandableListAdapter#getChildrenCount(int)
     */
    @Override
    public int getChildrenCount(int groupPosition) {
        if(group_list.get(groupPosition).itemList!=null){
            return group_list.get(groupPosition).itemList.size();
        }else{
            return 0;
        }
//        return group_list.size();
    }

    /**
     * 获取指定组中的数据
     *
     * @param groupPosition
     * @return
     * @see android.widget.ExpandableListAdapter#getGroup(int)
     */
    @Override
    public Object getGroup(int groupPosition) {
        return group_list.get(groupPosition);
    }

    /**
     * 获取指定组中的指定子元素数据。
     *
     * @param groupPosition
     * @param childPosition
     * @return
     * @see android.widget.ExpandableListAdapter#getChild(int, int)
     */
    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return group_list.get(groupPosition).itemList.get(childPosition);
    }

    /**
     * 获取指定组的ID，这个组ID必须是唯一的
     *
     * @param groupPosition
     * @return
     * @see android.widget.ExpandableListAdapter#getGroupId(int)
     */
    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    /**
     * 获取指定组中的指定子元素ID
     *
     * @param groupPosition
     * @param childPosition
     * @return
     * @see android.widget.ExpandableListAdapter#getChildId(int, int)
     */
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    /**
     * 组和子元素是否持有稳定的ID,也就是底层数据的改变不会影响到它们。
     *
     * @return
     * @see android.widget.ExpandableListAdapter#hasStableIds()
     */
    @Override
    public boolean hasStableIds() {
        return true;
    }

    /**
     * 获取显示指定组的视图对象
     *
     * @param groupPosition 组位置
     * @param isExpanded    该组是展开状态还是伸缩状态
     * @param convertView   重用已有的视图对象
     * @param parent        返回的视图对象始终依附于的视图组
     * @return
     * @see android.widget.ExpandableListAdapter#getGroupView(int, boolean, View,
     * ViewGroup)
     */
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        GroupHolder groupHolder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_all_cart, null);
            groupHolder = new GroupHolder();
            groupHolder.rl_multiple = (RelativeLayout) convertView.findViewById(R.id.rl_multiple);
            groupHolder.rl_simple = (RelativeLayout) convertView.findViewById(R.id.rl_simple);
            groupHolder.ll_multiple = (LinearLayout) convertView.findViewById(R.id.ll_multiple);
            groupHolder.cb_img = (CheckBox) convertView.findViewById(R.id.cb_img);
            groupHolder.cb_simple_img = (CheckBox) convertView.findViewById(R.id.cb_simple_img);
            groupHolder.edit_simple_total = (EditText) convertView.findViewById(R.id.edit_simple_total);
            groupHolder.txt_simple_money = (TextView) convertView.findViewById(R.id.txt_simple_money);
            groupHolder.txt_money = (TextView) convertView.findViewById(R.id.txt_money);
            groupHolder.img_simple_good=(ImageView) convertView.findViewById(R.id.img_simple_good);
            groupHolder.btn_simple_sub = (ImageView) convertView.findViewById(R.id.btn_simple_sub);
            groupHolder.btn_simple_add = (ImageView) convertView.findViewById(R.id.btn_simple_add);
            groupHolder.txt_name= (TextView) convertView.findViewById(R.id.txt_name);
            groupHolder.txt_simple_name=(TextView) convertView.findViewById(R.id.txt_simple_name);
            groupHolder.btn_simple_delete = (ImageView) convertView.findViewById(R.id.btn_simple_delete);
            groupHolder.btn_delete = (ImageView) convertView.findViewById(R.id.btn_delete);
            groupHolder.txt_expand=(TextView) convertView.findViewById(R.id.txt_expand);
            convertView.setTag(groupHolder);
        } else {
            groupHolder = (GroupHolder) convertView.getTag();
        }
//       ===================================================================== 设置第一种布局，套餐布局========================================================================================================
        AllCart item = group_list.get(groupPosition);
        if (item.type == 1) {
            groupHolder.rl_multiple.setVisibility(View.VISIBLE);
            groupHolder.rl_simple.setVisibility(View.GONE);
            groupHolder.cb_img.setChecked(item.isSelect);
            groupHolder.txt_name.setText(item.title);
            int total = 0;
            for (int i = 0, size = item.itemList.size(); i < size; i++) {
                if(item.itemList.get(i).isSelect) {
                    total += item.itemList.get(i).total_money;
                }
            }
            groupHolder.txt_money.setText("套餐价：￥" + total);
            groupHolder.btn_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setMessage("您确定要删除吗？");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            HomeCartManager.local.remove(item.unitId);
                            update(HomeCartManager.cartList);
                            dialog.dismiss();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    //    显示出该对话框
                    builder.show();
                }
            });
            groupHolder.cb_img.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    HomeCartManager.cartList.get(groupPosition).isSelect = isChecked;
                        for (int i = 0, size = HomeCartManager.cartList.get(groupPosition).itemList.size(); i < size; i++) {
                            HomeCartManager.cartList.get(groupPosition).itemList.get(i).isSelect = isChecked;
                        }
                    update(HomeCartManager.cartList);
                }
            });
        }
        //       ===================================================================== 设置第一种布局，套餐布局========================================================================================================


//        ===================================================================== 设置第二种布局，单品布局========================================================================================================
        else if (item.type == 2) {
            groupHolder.rl_multiple.setVisibility(View.GONE);
            groupHolder.rl_simple.setVisibility(View.VISIBLE);
            groupHolder.cb_simple_img.setChecked(item.isSelect);
            groupHolder.edit_simple_total.setText(item.number + "");
            groupHolder.txt_simple_money.setText("￥" + item.money);
            groupHolder.txt_simple_name.setText(item.title);
            Glide.with(context).load(item.image).into(groupHolder.img_simple_good);
            groupHolder.btn_simple_sub.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int num = HomeCartManager.cartList.get(groupPosition).number;
                    if (num <= 1) {
                        return;
                    }
                    num--;
                    HomeCartManager.cartList.get(groupPosition).number = num; //修改集合中商品数量
                    HomeCartManager.cartList.get(groupPosition).money = (HomeCartManager.cartList.get(groupPosition).one_money * num); //修改集合中该商品总价 数量*单价
                    //解决问题：点击某个按钮的时候，如果列表项所需的数据改变了，如何更新UI
                    update(HomeCartManager.cartList);
                }
            });
            groupHolder.btn_simple_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int num = HomeCartManager.cartList.get(groupPosition).number;
                    num++;
                    HomeCartManager.cartList.get(groupPosition).number = num; //修改集合中商品数量
                    HomeCartManager.cartList.get(groupPosition).money = (HomeCartManager.cartList.get(groupPosition).one_money * num); //修改集合中该商品总价 数量*单价
                    //解决问题：点击某个按钮的时候，如果列表项所需的数据改变了，如何更新UI
                    update(HomeCartManager.cartList);
                }
            });
            groupHolder.btn_simple_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setMessage("您确定要删除" + group_list.get(groupPosition).title + "吗？");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            HomeCartManager.local.remove(item.unitId);
                            update(HomeCartManager.cartList);
                            dialog.dismiss();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    //    显示出该对话框
                    builder.show();
                }
            });
            groupHolder.edit_simple_total.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (hasFocus) {
                        Object tag = v.getTag();
                        ((EditText) v).addTextChangedListener(new TextWatcher() {
                            @Override
                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                            }

                            @Override
                            public void onTextChanged(CharSequence s, int start, int before, int count) {

                            }

                            @Override
                            public void afterTextChanged(Editable s) {
                                if (s.toString().equals("")) {
                                    ((EditText) v).setText("1");
                                }
                                if (tag != null && tag instanceof Integer) {
                                    int position = (Integer) tag;
                                    HomeCartManager.cartList.get(position).number = Integer.parseInt(((EditText) v).getText().toString());
                                    HomeCartManager.cartList.get(position).money = (HomeCartManager.cartList.get(position).one_money * HomeCartManager.cartList.get(position).number);
                                }
                            }
                        });
                    } else {
                        update(HomeCartManager.cartList);
                    }
                }
            });
            groupHolder.edit_simple_total.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_DONE
                            || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        InputMethodManager imm = (InputMethodManager) context.
                                getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                        return true;
                    }
                    return false;
                }
            });
            groupHolder.cb_simple_img.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    HomeCartManager.cartList.get(groupPosition).isSelect = isChecked;
                    update(HomeCartManager.cartList);
                }
            });
            groupHolder.btn_simple_sub.setTag(groupPosition);
            groupHolder.btn_simple_add.setTag(groupPosition);
            groupHolder.btn_simple_delete.setTag(groupPosition);
            groupHolder.edit_simple_total.setTag(groupPosition);
        }
//        ===================================================================== 设置第二种布局，单品布局========================================================================================================
        if (!isExpanded) {
            if (item.type == 1)
                groupHolder.ll_multiple.setVisibility(View.VISIBLE);
            groupHolder.txt_expand.setText("V");
//            换图标
        } else {
            if (item.type == 1)
                groupHolder.ll_multiple.setVisibility(View.GONE);
            groupHolder.txt_expand.setText("Λ");
        }
        //设置数据
        return convertView;
    }

    /**
     * 获取一个视图对象，显示指定组中的指定子元素数据。
     *
     * @param groupPosition 组位置
     * @param childPosition 子元素位置
     * @param isLastChild   子元素是否处于组中的最后一个
     * @param convertView   重用已有的视图(View)对象
     * @param parent        返回的视图(View)对象始终依附于的视图组
     * @return
     * @see android.widget.ExpandableListAdapter#getChildView(int, int, boolean, View,
     * ViewGroup)
     */
    /*==============================================================================================================================================================================================================*/
    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View
            convertView, ViewGroup parent) {
        ItemHolder itemHolder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_simple_cart1, null);
            itemHolder = new ItemHolder();
            itemHolder.rl_simple = (RelativeLayout) convertView.findViewById(R.id.rl_simple);
            itemHolder.btn_simple_sub = (ImageView) convertView.findViewById(R.id.btn_simple_sub);
            itemHolder.btn_simple_add = (ImageView) convertView.findViewById(R.id.btn_simple_add);
            itemHolder.btn_simple_delete = (ImageView) convertView.findViewById(R.id.btn_simple_delete);
            itemHolder.edit_simple_total = (EditText) convertView.findViewById(R.id.edit_simple_total);
            itemHolder.cb_simple_img = (CheckBox) convertView.findViewById(R.id.cb_simple_img);
            itemHolder.txt_money = (TextView) convertView.findViewById(R.id.txt_money);
            itemHolder.img_cb_simple_img_good= (ImageView) convertView.findViewById(R.id.img_cb_simple_img_good);
            itemHolder.txt_simple_name=(TextView) convertView.findViewById(R.id.txt_simple_name);
            convertView.setTag(itemHolder);
        } else {
            itemHolder = (ItemHolder) convertView.getTag();
        }
        HomeItemCart item = group_list.get(groupPosition).itemList.get(childPosition);
        itemHolder.rl_simple.setVisibility(View.VISIBLE);
        itemHolder.cb_simple_img.setChecked(item.isSelect);
        itemHolder.edit_simple_total.setText(item.num + "");
        itemHolder.txt_simple_name.setText(item.title);
        itemHolder.txt_money.setText("￥" + item.total_money + "");
        Glide.with(context).load(item.image).into(itemHolder.img_cb_simple_img_good);

  /*=======================================================子布局设置监听=======================================================================================================================================*/
        itemHolder.btn_simple_sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num = HomeCartManager.cartList.get(groupPosition).itemList.get(childPosition).num;
                if (num <= 1) {
                    return;
                }
                num--;
                HomeCartManager.cartList.get(groupPosition).itemList.get(childPosition).num = num; //修改集合中商品数量
                HomeCartManager.cartList.get(groupPosition).itemList.get(childPosition).total_money = (HomeCartManager.cartList.get(groupPosition).itemList.get(childPosition).one_price * num); //修改集合中该商品总价 数量*单价
                //解决问题：点击某个按钮的时候，如果列表项所需的数据改变了，如何更新UI
                int total = 0;
                for (int i = 0, size = group_list.get(groupPosition).itemList.size(); i < size; i++) {
                    if (HomeCartManager.cartList.get(groupPosition).itemList.get(i).isSelect) {
                        total += HomeCartManager.cartList.get(groupPosition).itemList.get(i).total_money;
                    }
                }
                HomeCartManager.cartList.get(groupPosition).money = total;
                update(HomeCartManager.cartList);
            }
        });
        itemHolder.btn_simple_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num = HomeCartManager.cartList.get(groupPosition).itemList.get(childPosition).num;
                num++;
                HomeCartManager.cartList.get(groupPosition).itemList.get(childPosition).num = num; //修改集合中商品数量

                    HomeCartManager.cartList.get(groupPosition).itemList.get(childPosition).total_money = (HomeCartManager.cartList.get(groupPosition).itemList.get(childPosition).one_price * num); //修改集合中该商品总价 数量*单价
                    //解决问题：点击某个按钮的时候，如果列表项所需的数据改变了，如何更新UI

                int total = 0;
                for (int i = 0, size = group_list.get(groupPosition).itemList.size(); i < size; i++) {
                    if (HomeCartManager.cartList.get(groupPosition).itemList.get(i).isSelect) {
                        total += HomeCartManager.cartList.get(groupPosition).itemList.get(i).total_money;
                    }
                }
                HomeCartManager.cartList.get(groupPosition).money = total;
                update(HomeCartManager.cartList);
            }
        });
        itemHolder.btn_simple_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setMessage("您确定要删除" +item.title+ "吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        HomeCartManager.cartList.get(groupPosition).itemList.remove(childPosition);
                        int total = 0;
                        for (int i = 0, size = group_list.get(groupPosition).itemList.size(); i < size; i++) {
                            total += HomeCartManager.cartList.get(groupPosition).itemList.get(i).total_money;
                        }
                        HomeCartManager.cartList.get(groupPosition).money = total;
                        update(HomeCartManager.cartList);
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                //    显示出该对话框
                builder.show();
            }
        });
        itemHolder.edit_simple_total.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    ((EditText) v).addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            if (s.toString().equals("")) {
                                ((EditText) v).setText("1");
                            }
                            HomeCartManager.cartList.get(groupPosition).itemList.get(childPosition).num = Integer.parseInt(((EditText) v).getText().toString());
                            HomeCartManager.cartList.get(groupPosition).itemList.get(childPosition).total_money = (HomeCartManager.cartList.get(groupPosition).itemList.get(childPosition).one_price * HomeCartManager.cartList.get(groupPosition).itemList.get(childPosition).num);
                            int total = 0;
                            for (int i = 0, size = group_list.get(groupPosition).itemList.size(); i < size; i++) {
                                if(HomeCartManager.cartList.get(groupPosition).itemList.get(i).isSelect) {
                                    total += HomeCartManager.cartList.get(groupPosition).itemList.get(i).total_money;
                                }
                            }
                            HomeCartManager.cartList.get(groupPosition).money = total;
                        }
                    });
                } else {
                    update(HomeCartManager.cartList);
                }
            }
        });
        itemHolder.edit_simple_total.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    InputMethodManager imm = (InputMethodManager) context.
                            getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    return true;
                }
                return false;
            }
        });
        itemHolder.cb_simple_img.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                HomeCartManager.cartList.get(groupPosition).itemList.get(childPosition).isSelect=isChecked;
                    int total = 0;
                    for (int i = 0, size = group_list.get(groupPosition).itemList.size(); i < size; i++) {
                        if(HomeCartManager.cartList.get(groupPosition).itemList.get(i).isSelect) {
                            total += HomeCartManager.cartList.get(groupPosition).itemList.get(i).total_money;
                        }
                    }
                    HomeCartManager.cartList.get(groupPosition).money = total;
                update(HomeCartManager.cartList);
            }
        });
       /*==============================================================================================================================================================================================*/
        return convertView;
    }

    /**
     * 是否选中指定位置上的子元素。
     *
     * @param groupPosition
     * @param childPosition
     * @return
     * @see android.widget.ExpandableListAdapter#isChildSelectable(int, int)
     */
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }


    public void update(List<AllCart> group_list) {
        this.group_list = group_list;
        notifyDataSetChanged();
    }

    class GroupHolder {

        RelativeLayout rl_multiple;
        RelativeLayout rl_simple;
        LinearLayout ll_multiple;
        CheckBox cb_img;
        CheckBox cb_simple_img;
        EditText edit_simple_total;
        TextView txt_money;
        TextView txt_simple_money;
        ImageView btn_simple_sub;
        ImageView btn_simple_add;
        ImageView btn_simple_delete;
        ImageView btn_delete;
        ImageView img_simple_good;
        TextView txt_name;
        TextView txt_simple_name;
        TextView txt_expand;
    }

    class ItemHolder {
        RelativeLayout rl_simple;
        CheckBox cb_simple_img;
        TextView txt_money;
        ImageView btn_simple_sub;
        ImageView btn_simple_add;
        EditText edit_simple_total;
        ImageView btn_simple_delete;
        ImageView img_cb_simple_img_good;
        TextView txt_simple_name;
    }


}



